import React, { ChangeEvent, LegacyRef, forwardRef, useContext, useEffect, useImperativeHandle, useRef, useState } from 'react';
import CustomPopover from './CustomPopover';
import './custom-popover.scss';
import { Switch, Popconfirm, Input, InputRef, Button } from 'antd';
import { commonErrorMsg, commonSuccessMsg, deepCloneV2, deepCopy, defaultDocBaseConfigInfo, getChangeEventValue, isEmpty, toastShort } from '../../utils';
import TablePopover from './TablePopover';
import { ExpensesItemType } from '../../types';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';
import comDocContext from './../../context/DocContext';
import { DocConfig } from '../../utils/types';

interface Props {
    clientX: number
    clientY: number
}

const OtherExpensesPopover = (props: Props, ref: any) => {
    useImperativeHandle(ref, () => ({
        openPopover
    }))

    const {
        clientX,
        clientY
    } = props;

    const {
        comFocusTableCellList,
        comDocConfig,
        _setComDocConfig,
        comDocInstance,
        _setComDocInstance,
        comCellStyleConfig,
        _setComCellStyleConfig
    } = useContext(comDocContext);

    const [currentDocConfig, setCurrentDocConfig] = useState<DocConfig>({});

    const customSelectRef = useRef<any>(null);
    const lastOthterExpensesItemNameInputRef = useRef(null);

    useEffect(() => {
        const { docBaseConfigInfo } = comDocConfig;
        const {
            otherExpensesItemList = defaultDocBaseConfigInfo.otherExpensesItemList,
            basicReserveExpensesList = defaultDocBaseConfigInfo.basicReserveExpensesList
        } = docBaseConfigInfo;
        setOtherExpensesItemList([...otherExpensesItemList]);
        setBasicReserveExpensesList([...basicReserveExpensesList]);
        setCurrentDocConfig(comDocConfig);
    }, [comDocConfig])

    const openPopover = () => {
        customSelectRef.current.show();
    };

    const refCollect = useRef<{ [key: string]: InputRef }>({});

    const [otherExpensesItemList, setOtherExpensesItemList] = useState<ExpensesItemType[]>([
        {
            name: "勘查设计费用",
            value: 2.5
        },
        {
            name: "建设单位管理费",
            value: 2.0
        },
        {
            name: "工程监理费",
            value: 2.0
        },
        {
            name: "招标费",
            value: 0.5
        },
        {
            name: "",
            value: null,
        },
    ]);

    const [basicReserveExpensesList, setBasicReserveExpensesList] = useState<ExpensesItemType[]>([
        {
            name: "基本预备费",
            value: 5
        },
    ])

    const onOtherExpensesItemValueChange = (index: number, e: ChangeEvent<HTMLInputElement>) => {
        const tempOtherExpensesItemList = deepCopy(otherExpensesItemList);
        let _otherExpensesItemList = otherExpensesItemList;
        //@ts-ignore
        _otherExpensesItemList[index].value = getChangeEventValue(e);
        const tempTotalValue = getOtherExpensesTotalValue(_otherExpensesItemList);
        if (tempTotalValue > 100) {
            setOtherExpensesItemList([...tempOtherExpensesItemList])
            return toastShort('error', '费用占比不得超过工程费用100%')
        }
        setOtherExpensesItemList([..._otherExpensesItemList])
    }

    const onOtherExpensesItemNameChange = (index: number, e: ChangeEvent<HTMLInputElement>) => {
        let _otherExpensesItemList = otherExpensesItemList;
        _otherExpensesItemList[index].name = getChangeEventValue(e);
        setOtherExpensesItemList([..._otherExpensesItemList])
    }

    const onBaseExpensesItemValueChange = (index: number, e: ChangeEvent<HTMLInputElement>) => {
        const tempBasicReserveExpensesList = deepCopy(basicReserveExpensesList);
        let _baseReserveExpensesItemList = basicReserveExpensesList;
        //@ts-ignore
        _baseReserveExpensesItemList[index].value = getChangeEventValue(e);
        const tempTotalValue = getBaseExpensesTotalValue(_baseReserveExpensesItemList);
        if (tempTotalValue > 100) {
            setOtherExpensesItemList([...tempBasicReserveExpensesList])
            return toastShort('error', '费用占比不得超过工程费用100%')
        }
        setBasicReserveExpensesList([..._baseReserveExpensesItemList])
    }

    const onBaseExpensesItemNameChange = (index: number, e: ChangeEvent<HTMLInputElement>) => {
        let _baseReserveExpensesItemList = basicReserveExpensesList;
        _baseReserveExpensesItemList[index].name = getChangeEventValue(e);
        setBasicReserveExpensesList([..._baseReserveExpensesItemList])
    }
    

    const handleFocusInput = (index: number) => {
        refCollect.current[index + 'value'].focus();
    }

    const handleFocusNameInput = (index: number) => {
        refCollect.current[index + 'name'].focus();
    }

    const handleFocusBaseExpensesItemNameInput = (index: number) => {
        refCollect.current[index + 'name-1'].focus();
    }

    const handleFocusBaseExpensesItemValueInput = (index: number) => {
        refCollect.current[index + 'value-1'].focus();
    }

    const closePopover = () => {
        customSelectRef.current._handleClose();
    }

    const getOtherExpensesTotalValue = (_otherExpensesItemList?: ExpensesItemType[]): number => {
        let totalValue = 0;
        if (isEmpty(_otherExpensesItemList) || _otherExpensesItemList.length == 0) {
            _otherExpensesItemList = otherExpensesItemList;
        }
        _otherExpensesItemList.forEach(item => {
            totalValue += Number(item.value);
        })
        return totalValue;
    }

    const getBaseExpensesTotalValue = (_baseExpensesItemList?: ExpensesItemType[]): number => {
        let totalValue = 0;
        if (isEmpty(_baseExpensesItemList) || _baseExpensesItemList.length == 0) {
            _baseExpensesItemList = basicReserveExpensesList;
        }
        _baseExpensesItemList.forEach(item => {
            totalValue += Number(item.value);
        })
        return totalValue;
    }

    const deleteOtherExpensesItem = (index:number) => {
        let _otherExpensesItemList = otherExpensesItemList;
        _otherExpensesItemList.splice(index, 1);
        setOtherExpensesItemList([..._otherExpensesItemList])
    }   

    const confirmToAddOtherExpensesItem = (index:number) => {
        let _otherExpensesItemList = otherExpensesItemList;
        const _otherExpensesItemListLength = _otherExpensesItemList.length;
        const lastOtherExpensesItem = _otherExpensesItemList[_otherExpensesItemListLength - 1];
        if(isEmpty(lastOtherExpensesItem.name) && isEmpty(lastOtherExpensesItem.value)){
            return toastShort('error', '请先完善费用名称与占比')
        }
        _otherExpensesItemList.push({
            name: "",
            value: null,
        })
        setOtherExpensesItemList([..._otherExpensesItemList])
    }

    const handleConfirmChangeExpenses = () => {
        try{
            let _tempDocConfig = currentDocConfig;
            _tempDocConfig.docBaseConfigInfo.otherExpensesItemList = deepCloneV2(otherExpensesItemList);
            _tempDocConfig.docBaseConfigInfo.basicReserveExpensesList = deepCloneV2(basicReserveExpensesList);
            _tempDocConfig = deepCopy(_tempDocConfig);
            setCurrentDocConfig(_tempDocConfig);
            _setComDocConfig(_tempDocConfig);
            let _tempComDocInstance = comDocInstance;
            _tempComDocInstance.updateComponentName = 'EditPageNav';
            _setComDocInstance(_tempComDocInstance);
            closePopover();
            toastShort('success', commonSuccessMsg)
        }catch(e){
            toastShort('error', commonErrorMsg)
        }
    }

    return (
        <CustomPopover
            ref={customSelectRef}
            clientX={clientX}
            clientY={clientY}
            contentRender={(props) => (
                <div style={{ width: 320, pointerEvents: 'all', zIndex: 999999 }} className='insert-tools-popover'>
                    <div className='flex-row insert-tools-popover-title'>
                        <div>其它费用占比设置</div>
                        <div style={{ fontSize: 12 }}>({`按照工程费用的${getOtherExpensesTotalValue()}%估算`})</div>
                    </div>
                    <div className='flex-row insert-tools-content'>
                        {
                            otherExpensesItemList.map((item, index) => {
                                return (
                                    <div
                                        className='flex-row other-expenses-item'
                                        key={index + ''}
                                    >
                                        <div className='other-expenses-item-name'>
                                            <Input
                                                ref={c => { refCollect.current[index + 'name'] = c }}
                                                className='other-expenses-item-name-input'
                                                value={item.name}
                                                disabled={false}
                                                onClick={() => handleFocusNameInput(index)}
                                                onChange={(e) => onOtherExpensesItemNameChange(index, e)}
                                                maxLength={12}
                                                placeholder={'输入费用名称'}
                                            />
                                        </div>
                                        <Input
                                            ref={c => { refCollect.current[index + 'value'] = c }}
                                            className='other-expenses-item-input'
                                            addonAfter={'%'}
                                            value={item.value}
                                            disabled={false}
                                            type={'number'}
                                            onClick={() => handleFocusInput(index)}
                                            onChange={(e) => onOtherExpensesItemValueChange(index, e)}
                                            maxLength={12}
                                            placeholder={'输入费用占比'}
                                        />
                                        {
                                            index < otherExpensesItemList.length - 1 ?
                                                <Button
                                                    icon={<MinusOutlined />}
                                                    onClick={() => deleteOtherExpensesItem(index)}
                                                />
                                                :
                                                <Button
                                                    icon={<PlusOutlined />}
                                                    onClick={() => confirmToAddOtherExpensesItem(index)}
                                                />
                                        }
                                    </div>
                                )
                            })
                        }
                    </div>
                    <div style={{ marginTop: 12 }} className='flex-row insert-tools-popover-title'>
                        <div>基本预备费占比设置</div>
                        <div style={{ fontSize: 12 }}>({`按照工程费用的${getBaseExpensesTotalValue()}%估算`})</div>
                    </div>
                    <div className='flex-row insert-tools-content' style={{ paddingBottom: 12 }}>
                        {
                            basicReserveExpensesList.map((item, index) => {
                                return (
                                    <div
                                        className='flex-row other-expenses-item'
                                        key={index + ''}
                                    >
                                        <div className='other-expenses-item-name'>
                                            <Input
                                                ref={c => { refCollect.current[index + 'name-1'] = c }}
                                                className='other-expenses-item-name-input'
                                                value={item.name}
                                                disabled={false}
                                                onClick={() => handleFocusBaseExpensesItemNameInput(index)}
                                                onChange={(e) => onBaseExpensesItemNameChange(index, e)}
                                                maxLength={12}
                                                placeholder={'输入费用名称'}
                                            />
                                        </div>
                                        <Input
                                            ref={c => { refCollect.current[index + 'value-1'] = c }}
                                            className='other-expenses-item-input'
                                            addonAfter={'%'}
                                            value={item.value}
                                            disabled={false}
                                            type={'number'}
                                            onClick={() => handleFocusBaseExpensesItemValueInput(index)}
                                            onChange={(e) => onBaseExpensesItemValueChange(index, e)}
                                            maxLength={12}
                                            placeholder={'输入费用占比'}
                                        />
                                    </div>
                                )
                            })
                        }
                    </div>
                    <div className="flex-row other-expenses-popover-footer">
                        <Button
                            size={'small'}
                            onClick={closePopover}
                        >
                            取消
                        </Button>
                        <Button
                            size={'small'}
                            type={"primary"}
                            style={{ marginLeft: 12 }}
                            onClick={handleConfirmChangeExpenses}
                        >
                            确认
                        </Button>
                    </div>
                </div>
            )}
        />
    )
}


export default forwardRef(OtherExpensesPopover);